//
//  HMSinaTabBar.swift
//  ZJCSina
//
//  Created by 朱建超 on 16/11/12.
//  Copyright © 2016年 itHeiMa. All rights reserved.
//

import UIKit

class HMSinaTabBar: UITabBar {

    //定义闭包
    var addButtonClosure : (() -> ())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //添加按钮
        self.addSubview(addButton)
        //监听按钮的点击事件
        addButton.addTarget(self, action: #selector(addButtonClick), for: .touchUpInside)
    }
    
    @objc private func addButtonClick() {
        
        //对外抛出（代理或者闭包）
        addButtonClosure?()
    }
    
    //解档的方法
    required init?(coder aDecoder: NSCoder) {
        //默认实现报错
//        fatalError("init(coder:) has not been implemented")
        
        //让该控件支持手写代码和xib创建
        super.init(coder: aDecoder)
        self.addSubview(addButton)
    }
    
   //修改内部视图的位置，要冲写layoutSubviews
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        //获取UITabBarButton等控件，并且修改frame
        //遍历子视图
        let W = UIScreen.main.bounds.width / 5
        let H = self.bounds.height
        
        var index = 0
        
        for subViews in subviews {
            
            //判断类型
            if subViews.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                //修改frame
                subViews.frame = CGRect(x: CGFloat(index) * W, y: 0, width: W, height: H)
                
                if index == 1 {
                    index += 1
                }
                index += 1
            }
            
        }
        
        //设置按钮的frame
        addButton.bounds.size = CGSize(width: W, height: H)
        addButton.center = CGPoint(x: self.center.x, y: H * 0.5)
        
    }
    
    //懒加载按钮
    lazy var addButton: UIButton = {
        
        let button = UIButton()
        
        //设置图片
        button.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        button.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        //设置背景图片
        button.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
        
        return button
    }()

}
